package com.shixianjun.leetcode.剑指offer;

import com.shixianjun.tools.Tools;

public class _21_调整数组顺序使奇数位于偶数前面 {

    /**
     * 输入一个整数数组，实现一个函数来调整该数组中数字的顺序，使得所有奇数在数组的前半部分，所有偶数在数组的后半部分。
     * */
    static public int[] exchange(int[] nums) {

        if (nums.length <= 1) return nums;

        int left = 0;
        int right = nums.length - 1;

        while (left < right) {
            while (left < right && nums[left] % 2 == 1) {
                left++;
            }
            while (left < right && nums[right] % 2 == 0) {
                right--;
            }

            if (left < right) {
                int temp = nums[left];
                nums[left++] = nums[right];
                nums[right--] = temp;
            }
        }

        return nums;
    }

    public static void main(String[] args) {
        int[] numbers = new int[] {4, 7, 3, 6, 1, 4, 7, 8};
        int[] result = exchange(numbers);
        Tools.printIntArray("结果", result);
    }
}
